import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index.js'
import router from '@/router/index.js'
import { gettimestamp } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 从配置文件中设置基地址
  timeout: 5000
})
const TimeOut = 36000
// 请求拦截器
service.interceptors.request.use(config => {
// Do something before request is sent
  if (store.getters.token) {
    // 如果token超时，阻止请求
    if (judgetime()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token 过期'))
    }
    // 如果token存在 注入token
    config.headers['Authorization'] = `Bearer ${store.getters.token}`
  }
  return config
}, error => {
// Do something with request error
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
// Do something before response is sent
  const { data, success, message } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
// Do something with response error
  Message.error(error.message)// 错误提示
  if (error.response && error.response.data && error.request.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  return Promise.reject(error)// 返回执行错误 让当前的执行链跳出成功 直接进入 catch
})

// 判断token是否超时方法
function judgetime() {
  var currentTime = Date.now() // 当前时间戳
  var timeStamp = gettimestamp() // 缓存时间戳
  return (currentTime - timeStamp) / 1000 > TimeOut
}

export default service

